package com.sinping.qh.service.app.records.impl;

import com.google.common.collect.Lists;
import com.sinping.qh.api.exception.HandlerException;
import com.sinping.qh.api.support.ConstEum;
import com.sinping.qh.api.support.FrontPage;
import com.sinping.qh.api.support.ResDtoUtil;
import com.sinping.qh.domain.auth.Role;
import com.sinping.qh.domain.common.UnitDomain;
import com.sinping.qh.domain.common.UploadImage;
import com.sinping.qh.domain.lab.LaboratoryDomain;
import com.sinping.qh.domain.records.*;
import com.sinping.qh.domain.user.UserInfo;
import com.sinping.qh.domain.user.UserLaboratory;
import com.sinping.qh.dto.app.records.*;
import com.sinping.qh.dto.app.user.UserInfoNoContentDTO;
import com.sinping.qh.dto.common.CommonDTO;
import com.sinping.qh.dto.common.ICommonDTO;
import com.sinping.qh.dto.common.UploadImageDTO;
import com.sinping.qh.query.records.CheckRecoredsQuery;
import com.sinping.qh.repository.mongo.UnitRepository;
import com.sinping.qh.repository.mongo.common.UploadImageRepository;
import com.sinping.qh.repository.mongo.lab.LaboratoryRepository;
import com.sinping.qh.repository.mongo.records.CheckPlanRepository;
import com.sinping.qh.repository.mongo.records.CheckRecordsRepository;
import com.sinping.qh.repository.mongo.records.HiddenDangerRecordRepository;
import com.sinping.qh.repository.mongo.records.HighLightRepository;
import com.sinping.qh.repository.mongo.records.impl.CheckRecordsRepositoryImpl;
import com.sinping.qh.repository.mongo.user.UserInfoRepository;
import com.sinping.qh.repository.mongo.user.UserLaboratoryRepository;
import com.sinping.qh.service.MongoManager;
import com.sinping.qh.service.app.records.ICheckRecordService;
import com.sinping.qh.service.auth.IRoleService;
import com.sinping.qh.service.base.BaseService;
import com.sinping.qh.service.common.CommonDbConst;
import com.sinping.qh.utils.mapper.BeanMapper;
import com.sinping.qh.utils.misc.IdGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author zhangjin
 * @create 2018/5/31
 */
@Service
public class CheckRecordServiceImpl extends BaseService implements ICheckRecordService {


    @Autowired
    MongoManager mongoManager;

    @Autowired
    CheckRecordsRepository checkRecordsRepository;

    @Autowired
    CheckPlanRepository checkPlanRepository;

    @Autowired
    HiddenDangerRecordRepository hiddenDangerRecordRepository;

    @Autowired
    HighLightRepository highLightRepository;

    @Autowired
    CheckRecordsRepositoryImpl recordsRepository;

    @Autowired
    UnitRepository unitRepository;

    @Autowired
    LaboratoryRepository laboratoryRepository;

    @Autowired
    UserLaboratoryRepository userLaboratoryRepository;

    @Autowired
    UserInfoRepository userInfoRepository;

    @Autowired
    IRoleService iRoleService;

    @Autowired
    private UploadImageRepository imageRepository;

    @Value(value = "${qh.upload.urlPath}")
    private String urlPath;


    @Override
    public FrontPage findPage(FrontPage frontPage) {

        Sort sort=new Sort(Sort.Direction.ASC,"check_type","check_room");
        if(StringUtils.isNotBlank(frontPage.getProp()) &&
                StringUtils.isNotBlank(frontPage.getOrder()))
        {
            sort.and(new Sort(Sort.Direction.fromString(frontPage.getOrder()),frontPage.getProp()));
        }else
        {
            sort.and(new Sort(Sort.Direction.DESC,"gmt_created"));
        }
        //查询条件
        CheckRecoredsQuery checkRecoredsQuery = BeanMapper.map(frontPage,CheckRecoredsQuery.class);
        PageRequest page = new PageRequest(frontPage.getPage()-1,frontPage.getSize(),sort);

        //查询检查记录
        Page<CheckRecord> checkRecords =mongoManager.findPage(checkRecoredsQuery,page,CheckRecord.class);

        frontPage=ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(checkRecords,CheckRecordByAppDTO.class,frontPage);

        List<CheckRecordByAppDTO<CheckRecordLabInfoByAppDTO>> checkRecordByAppDTOList=frontPage.getRecords();
        //实验室检查去查询负责人
        for(CheckRecordByAppDTO checkRecordByAppDTO:checkRecordByAppDTOList){
            if(checkRecordByAppDTO.getCheckType().equals(CommonDbConst.CHECKRECORD_TYPE_LAB)) {
                //根据检查记录的实验室id查询实验室的安全负责人
                LaboratoryDomain laboratoryDomain=
                        laboratoryRepository.findOne(checkRecordByAppDTO.getCheckLabId());

                if(laboratoryDomain!=null) {
                    CheckRecordLabInfoByAppDTO checkRecordLabInfoByAppDTO =
                            new CheckRecordLabInfoByAppDTO();

                    //实验室负责人
                    checkRecordLabInfoByAppDTO.setRiskManager(laboratoryDomain.getRiskManager());
                    //实验室负责人电话
                    checkRecordLabInfoByAppDTO.setTelephone(laboratoryDomain.getTelephone());


                    //根据检查记录的实验室id查询用户实验表的负责人,并且这个负责人的角色是安全员

                    List<UserLaboratory> userLaboratoryList =
                            userLaboratoryRepository.findAllByManagerLabId(laboratoryDomain.getId());

                    List<UserInfoNoContentDTO> userInfoNoContentDTOList =
                            new ArrayList<>();
                    for (UserLaboratory userLaboratory : userLaboratoryList) {
                        //如果用户是安全员则加入
                        UserInfo userInfo =
                                userInfoRepository.findOne(userLaboratory.getUserId());
                        if(userInfo!=null) {
                            Role role = iRoleService.selectById(userInfo.getRoleId());

                            if (role != null && role.getSecurity().equals(CommonDbConst.SECURITY_YES)) {
                                UserInfoNoContentDTO userInfoNoContentDTO
                                        = BeanMapper.map(userInfo, UserInfoNoContentDTO.class);

                                userInfoNoContentDTOList.add(userInfoNoContentDTO);
                            }
                        }
                    }

                    checkRecordLabInfoByAppDTO.setLabManager(userInfoNoContentDTOList);

                    checkRecordByAppDTO.setItems(checkRecordLabInfoByAppDTO);
                }else
                {
                    checkRecordByAppDTO.setItems(new CheckRecordLabInfoByAppDTO());
                }
            }
        }
        frontPage.setRecords(checkRecordByAppDTOList);

        return frontPage;
    }

    /**
     * 一、查询的数据,查询自己所属院或者所属实验室的数据，并且
     *     1.1隐患数据不为能0
     *     1.2隐患不能全部已完成
     * 进行分组，显示条数
     * @param frontPage
     * @param commonDTO
     * @return
     */
    @Override
    public FrontPage findPageByUniting(FrontPage frontPage,ICommonDTO commonDTO) {

        Sort sort;
        if(StringUtils.isNotBlank(frontPage.getProp()) &&
                StringUtils.isNotBlank(frontPage.getOrder()))
        {
            sort=new Sort(Sort.Direction.fromString(frontPage.getOrder()),frontPage.getProp());
        }else
        {
            sort = new Sort(Sort.Direction.DESC,"gmt_modified");
        }
        //查询条件
        PageRequest page = new PageRequest(frontPage.getPage()-1,frontPage.getSize(),sort);

        //分组条件
        List<String> groupParams = Lists.newArrayList("check_unit_id","check_unit",
                "check_building_id", "check_building");

        List<String> unitIDLists=
                getUnitIDLists(userLaboratoryRepository,((CommonDTO)commonDTO).getUserSessionDTO().getUserInfo().getId());

        List<String> labIDLists=
                getLabIDLists(userLaboratoryRepository,((CommonDTO)commonDTO).getUserSessionDTO().getUserInfo().getId());

        List<CheckRecordGroupByAppDTO> checkRecordGroupByAppDTOListByPage=
                recordsRepository.findPageByUniting(unitIDLists,labIDLists,
                        groupParams,page,CheckRecord.class,CheckRecordGroupByAppDTO.class);

        List<CheckRecordGroupByAppDTO> checkRecordGroupByAppDTOListByNoPage=
                recordsRepository.findPageByUniting(unitIDLists,labIDLists,
                        groupParams,null,CheckRecord.class,CheckRecordGroupByAppDTO.class);

        //如果不使用分页的内容将会查询时有问题
        Page<CheckRecordGroupByAppDTO> pages=new PageImpl<>(checkRecordGroupByAppDTOListByPage, page,
                checkRecordGroupByAppDTOListByNoPage.size());
        frontPage=ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(pages,CheckRecordGroupByAppDTO.class,frontPage);
        return frontPage;
    }

    @Override
    public FrontPage findPageByUnitingDetail(FrontPage frontPage,ICommonDTO commonDTO) {

        Sort sort =new Sort(Sort.Direction.DESC,"check_date","check_type","check_room");
        if(StringUtils.isNotBlank(frontPage.getProp()) &&
                StringUtils.isNotBlank(frontPage.getOrder()))
        {
            sort.and(new Sort(Sort.Direction.fromString(frontPage.getOrder()),frontPage.getProp()));
        }else
        {
            sort = sort.and(new Sort(Sort.Direction.DESC,"gmt_created"));
        }
//        //查询条件
        PageRequest page = new PageRequest(frontPage.getPage()-1,frontPage.getSize(),sort);

        List<String> unitIDLists=
                getUnitIDLists(userLaboratoryRepository,((CommonDTO)commonDTO).getUserSessionDTO().getUserInfo().getId());

        List<String> labIDLists=
                getLabIDLists(userLaboratoryRepository,((CommonDTO)commonDTO).getUserSessionDTO().getUserInfo().getId());

        List<CheckRecord> checkRecordListByPage=
                recordsRepository.findPageByUnitingDetail(unitIDLists,labIDLists,
                        frontPage.getCheckUnitId(),frontPage.getCheckBuildingId(),
                        page,
                        CheckRecord.class);

        List<CheckRecord> checkRecordListByNoPage=
                recordsRepository.findPageByUnitingDetail(unitIDLists,labIDLists,
                        frontPage.getCheckUnitId(),frontPage.getCheckBuildingId(),
                        null,
                        CheckRecord.class);

        Page<CheckRecord> CheckRecords=new PageImpl<>(checkRecordListByPage, page, checkRecordListByNoPage.size());

        frontPage=ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(CheckRecords,CheckRecordByAppDTO.class,frontPage);

        List<CheckRecordByAppDTO<CheckRecordHiddenCountByAppDTO>> checkRecordByAppDTOList
                = frontPage.getRecords();

        ArrayList arrayList =new ArrayList();
        arrayList.add("0");
        arrayList.add("1");
        arrayList.add("2");
        //根据检查记录去查询下面的隐患记录
        for (CheckRecordByAppDTO<CheckRecordHiddenCountByAppDTO> checkRecordByAppDTO:checkRecordByAppDTOList) {

            CheckRecordHiddenCountByAppDTO checkRecordChild = new CheckRecordHiddenCountByAppDTO();
            List<HiddendangerRecord> hiddendangerRecords
                    =hiddenDangerRecordRepository.
                    findHiddendangerRecordsByCheckId(
                            checkRecordByAppDTO.getId());
            if(hiddendangerRecords.size()>0) {

                int readyRectify = 0;
                int failRectify = 0;
                int readyReview = 0;
                int close = 0;
                for (HiddendangerRecord hiddendangerRecord : hiddendangerRecords) {

                    switch (hiddendangerRecord.getHiddenDangerStatus()) {
                        case CommonDbConst.HIDDENDANGER_STATUS_READY_RECTIFY:
                            readyRectify++;
                            break;
                        case CommonDbConst.HIDDENDANGER_STATUS_FAIL_RECTIFY:
                            failRectify++;
                            break;
                        case CommonDbConst.HIDDENDANGER_STATUS_READY_REVIEW:
                            readyReview++;
                            break;
                        case CommonDbConst.HIDDENDANGER_STATUS_CLOSE:
                            close++;
                            break;
                    }
                }

                checkRecordChild.setHiddenDangerCount(hiddendangerRecords.size() + "");
                //待整改
                checkRecordChild.setHiddenDanger_Ready_Rectify(readyRectify + "");
                //不到位
                checkRecordChild.setHiddenDanger_Fail_Rectify(failRectify + "");
                //待复查
                checkRecordChild.setHiddenDanger_ReadyReview(readyReview + "");
                //己整改
                checkRecordChild.setHiddenDanger_Close(close + "");

            }
            checkRecordByAppDTO.setItems(checkRecordChild);
        }

        frontPage.setRecords(checkRecordByAppDTOList);

       return frontPage;
    }

    @Override
    public FrontPage findPageByRectifyAndReview(FrontPage frontPage,ICommonDTO commonDTO) {

        Sort sort;
        if(StringUtils.isNotBlank(frontPage.getProp()) &&
                StringUtils.isNotBlank(frontPage.getOrder()))
        {
            sort=new Sort(Sort.Direction.fromString(frontPage.getOrder()),frontPage.getProp());
        }else
        {
            sort = new Sort(Sort.Direction.DESC,"gmt_created");
        }
        //查询条件
        PageRequest page = new PageRequest(frontPage.getPage()-1,frontPage.getSize(),sort);


        List<String> unitIDLists=
                getUnitIDLists(userLaboratoryRepository,((CommonDTO)commonDTO).getUserSessionDTO().getUserInfo().getId());

        List<String> labIDLists=
                getLabIDLists(userLaboratoryRepository,((CommonDTO)commonDTO).getUserSessionDTO().getUserInfo().getId());

        List<CheckRecord> checkRecordListByPage=
                recordsRepository.findPageByRectifyAndReview(unitIDLists,labIDLists,
                        frontPage.getCheckStatus(),
                        frontPage,
                        page,
                        CheckRecord.class);

        List<CheckRecord> checkRecordListByNoPage=
                recordsRepository.findPageByRectifyAndReview(unitIDLists,labIDLists,
                        frontPage.getCheckStatus(),
                        frontPage,
                        null,
                        CheckRecord.class);

        Page<CheckRecord> CheckRecords=new PageImpl<>(checkRecordListByPage, page, checkRecordListByNoPage.size());

        frontPage=ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(CheckRecords,CheckRecordByAppDTO.class,frontPage);

        List<CheckRecordByAppDTO<CheckRecordHiddenCountByAppDTO>> checkRecordByAppDTOList
                = frontPage.getRecords();

        ArrayList arrayList =new ArrayList();
        arrayList.add("0");
        arrayList.add("1");
        arrayList.add("2");
        //根据检查记录去查询下面的隐患记录
        for (CheckRecordByAppDTO<CheckRecordHiddenCountByAppDTO> checkRecordByAppDTO:checkRecordByAppDTOList) {

            CheckRecordHiddenCountByAppDTO checkRecordChild = new CheckRecordHiddenCountByAppDTO();
            List<HiddendangerRecord> hiddendangerRecords
                    =hiddenDangerRecordRepository.
                    findHiddendangerRecordsByCheckId(checkRecordByAppDTO.getId());
            if(hiddendangerRecords.size()>0) {

                int readyRectify = 0;
                int failRectify = 0;
                int readyReview = 0;
                int close = 0;
                for (HiddendangerRecord hiddendangerRecord : hiddendangerRecords) {

                    switch (hiddendangerRecord.getHiddenDangerStatus()) {
                        case CommonDbConst.HIDDENDANGER_STATUS_READY_RECTIFY:
                            readyRectify++;
                            break;
                        case CommonDbConst.HIDDENDANGER_STATUS_FAIL_RECTIFY:
                            failRectify++;
                            break;
                        case CommonDbConst.HIDDENDANGER_STATUS_READY_REVIEW:
                            readyReview++;
                            break;
                        case CommonDbConst.HIDDENDANGER_STATUS_CLOSE:
                            close++;
                            break;
                    }
                }

                checkRecordChild.setHiddenDangerCount(hiddendangerRecords.size() + "");
                //待整改
                checkRecordChild.setHiddenDanger_Ready_Rectify(readyRectify + "");
                //不到位
                checkRecordChild.setHiddenDanger_Fail_Rectify(failRectify + "");
                //待复查
                checkRecordChild.setHiddenDanger_ReadyReview(readyReview + "");
                //己整改
                checkRecordChild.setHiddenDanger_Close(close + "");

            }
            checkRecordByAppDTO.setItems(checkRecordChild);

        }

        frontPage.setRecords(checkRecordByAppDTOList);
        return frontPage;
    }

    @Override
    public CheckRecordByAppDTO findOne(String id) {

        CheckRecord checkRecord =checkRecordsRepository.findOne(id);
        CheckRecordByAppDTO<HighLightByAppDTO> checkRecordByAppDTO= BeanMapper.map(checkRecord,CheckRecordByAppDTO.class);

        HighLightRecord highLightRecord=
                highLightRepository.findHighLightRecordByCheckId(checkRecordByAppDTO.getId());

        if(highLightRecord!=null && highLightRecord.getUploadImageList().size()>0)
        {
            List<UploadImage> uploadImageDTOList=
                    highLightRecord.getUploadImageList();

            for (UploadImage uploadImage:uploadImageDTOList)
            {
                uploadImage.setPath(urlPath+uploadImage.getPath());
            }
        }

        if(highLightRecord!=null) {
            HighLightByAppDTO highLightByAppDTO = BeanMapper.map(highLightRecord, HighLightByAppDTO.class);

            checkRecordByAppDTO.setItems(highLightByAppDTO);
        }
        return checkRecordByAppDTO;
    }

    /**
     * 删除检查记录：状态为未检查
        物理删除
     * @param id
     * @return
     */
    @Override
    public boolean delete(String id) {
        CheckRecord checkRecord=checkRecordsRepository.findOne(id);
        if(checkRecord.getCheckStatus().equals(CommonDbConst.CHECKRECORD_STATUS_UNCHECK)) {
            checkRecordsRepository.delete(id);
        }
        else
        {
            throw new HandlerException(ConstEum.FAIL,"记录状态已变更,不能删除");
        }
        return true;
    }

    /**
     * 需要处理自动审核的检查记录
     * 一、开始检查时要添加院系参加人员和检查人员
     * @param id
     * @param checkStatus
     * @return
     */
    @Override
    public boolean examineCheckRecord(String id, String checkStatus) {

        String newCheckStatus=checkStatus;
        CheckRecord checkRecord =checkRecordsRepository.findOne(id);

        CheckPlan checkPlan = checkPlanRepository.findOne(checkRecord.getCheckPlanId());
        if(checkRecord==null)
        {
            throw new HandlerException(ConstEum.FAIL,"未找到检查记录");
        }

        switch (checkStatus){
            //未检查
            case CommonDbConst.CHECKRECORD_STATUS_UNCHECK:

                break;
            //检查中
            case CommonDbConst.CHECKRECORD_STATUS_CHECKING:
                //修改检查日期
                checkRecord.setCheckDate(new Date());
                //检查人员
                checkRecord.setCheckUser(checkPlan.getCheckUser());
                //院系参加人员
                checkRecord.setUnionUnitUser(checkPlan.getUnionUnitUser());
                break;
            //待审核
            case CommonDbConst.CHECKRECORD_STATUS_READY_AUDIT:
                //查找自动审核的院系
                UnitDomain unitDomain=
                        unitRepository.findUnitDomainByIdAndIsAutomaticAndStatus
                                (checkRecord.getCheckUnitId(),"1",CommonDbConst.DB_DELETE_NORMAL);
                if(unitDomain!=null)
                {
                    newCheckStatus=CommonDbConst.CHECKRECORD_STATUS_CLOSE_AUDIT;
                }
                break;
            //己审核
            case CommonDbConst.CHECKRECORD_STATUS_CLOSE_AUDIT:
                break;

        }
        checkRecord.setCheckStatus(newCheckStatus);
        checkRecord.setGmtModified(new Date());
        checkRecord=checkRecordsRepository.save(checkRecord);
        if(checkRecord!=null)
        {
            List<HiddendangerRecord> hiddendangerRecordList=
                    hiddenDangerRecordRepository.findHiddendangerRecordsByCheckId(id);
            for (HiddendangerRecord hiddendangerRecord:hiddendangerRecordList) {

                hiddendangerRecord.setCheckStatus(newCheckStatus);
                hiddenDangerRecordRepository.save(hiddendangerRecord);
            }
            return true;
        }
        else
        {
            throw new HandlerException(ConstEum.FAIL,ConstEum.FAIL.getMessage());
        }
    }
    @Override
    public void updateRecordByOffline(CheckRecordOffLineByAppDTO checkRecordOffLineByAppDTO,ICommonDTO iCommonDTO){

        /****************************************************************
         ****************************离线检查验证区***********************
         ****************************************************************/
        CheckRecord checkRecord=checkRecordsRepository.findOne(checkRecordOffLineByAppDTO.getId());
        if(checkRecord==null)
        {
            throw new HandlerException(ConstEum.SUCCESS,"找不到检查记录");
        }
        CheckPlan checkPlan = checkPlanRepository.findOne(checkRecord.getCheckPlanId());
        if(checkPlan==null)
        {
            throw new HandlerException(ConstEum.FAIL,"找不到检查计划");
        }

        //检查状态必须为未审核或者已经审核
        if((checkRecord.getCheckStatus().equals(CommonDbConst.CHECKRECORD_STATUS_READY_AUDIT))
                ||(checkRecord.getCheckStatus().equals(CommonDbConst.CHECKRECORD_STATUS_CLOSE_AUDIT)))
        {
            throw new HandlerException(ConstEum.SUCCESS,"检查记录已提交审核或已经审核");
        }

        //检查人员
        if (checkRecordOffLineByAppDTO.getCheckUser().size() > 0) {
            if (checkPlan.getCreateUserId().equals(((CommonDTO) iCommonDTO).getUserSessionDTO().getUserInfo().getId())) {
//                checkRecord.setCheckUser(checkRecordOffLineByAppDTO.getCheckUser());
            } else {
//                throw new HandlerException(ConstEum.FAIL,"只能创建人可以修改检查人员");
            }
        } else {
            throw new HandlerException(ConstEum.FAIL, "检查人员不能为空");
        }
        checkRecord.setCheckUser(checkRecordOffLineByAppDTO.getCheckUser());

        if(checkRecordOffLineByAppDTO.getHiddendangerByAppDTOS()!=null &&
                checkRecordOffLineByAppDTO.getHiddendangerByAppDTOS().size()>0) {
            for (HiddendangerByAppDTO hiddendangerByAppDTO : checkRecordOffLineByAppDTO.getHiddendangerByAppDTOS()) {

                if (StringUtils.isEmpty(hiddendangerByAppDTO.getDesc()) && StringUtils.isEmpty(hiddendangerByAppDTO.getCheckItemThreeId())) {
                    throw new HandlerException(ConstEum.FAIL, "隐患描述不能为空");
                }
            }
        }
//        if(checkRecordOffLineByAppDTO.getHiddendangerByAppDTOS()!=null &&
//                checkRecordOffLineByAppDTO.getHiddendangerByAppDTOS().size()>0){
//            for (HiddendangerByAppDTO hiddendangerByAppDTO:checkRecordOffLineByAppDTO.getHiddendangerByAppDTOS()){
//
//                if (StringUtils.isNotBlank(hiddendangerByAppDTO.getId())) {
//                    HiddendangerRecord hiddendangerRecord = hiddenDangerRecordRepository.findOne(hiddendangerByAppDTO.getId());
//                    if (hiddendangerRecord == null) {
//                        throw new HandlerException(ConstEum.FAIL, "错误的隐患Id");
//                    }
//                }
//            }
//        }

        /****************************************************************
         ****************************离线检查数据处理区***********************
         ****************************************************************/
        switch (checkRecord.getCheckStatus()) {
            //未检查
            case CommonDbConst.CHECKRECORD_STATUS_UNCHECK:

                checkRecord.setCheckStatus(CommonDbConst.CHECKRECORD_STATUS_CHECKING);
                checkRecord.setCheckDate(checkRecordOffLineByAppDTO.getCheckDate());
                break;
            //检查中
            case CommonDbConst.CHECKRECORD_STATUS_CHECKING:
                break;
        }
        checkRecord.setUnionUnitUser(checkRecordOffLineByAppDTO.getUnionUnitUser());
        checkRecord.setGmtModified(new Date());
        CheckRecord newCheckRecord =checkRecordsRepository.save(checkRecord);
        if(newCheckRecord==null)
        {
            throw new HandlerException(ConstEum.FAIL, ConstEum.FAIL.getMessage());
        }

        HighLightByAppDTO highLightByAppDTO =checkRecordOffLineByAppDTO.getItems();

        String hightLightId="";
        if(highLightByAppDTO!=null) {
//            if (StringUtils.isNotBlank(highLightByAppDTO.getId())) {
//
//                HighLightRecord highLightRecord = highLightRepository.findOne(highLightByAppDTO.getId());
//                if (highLightRecord == null) {
////                throw new HandlerException(ConstEum.FAIL,"错误的亮点Id");
//                    try {
//                        highLightRepository.deleteByCheckId(checkRecord.getId());
//                    }catch (Exception e){}
//                } else {
//                    hightLightId=highLightByAppDTO.getId();
//                    highLightRepository.delete(highLightRecord.getId());
//                }
//            }
            //添加之前删除下面所有的亮点
            List<HighLightRecord> highLightRecordList=
                    highLightRepository.findAllByCheckId(checkRecord.getId());
            for (HighLightRecord highLightRecord:highLightRecordList){
                hightLightId=highLightRecord.getId();
                highLightRepository.delete(highLightRecord.getId());
            }
            HighLightRecord highLightRecord = BeanMapper.map(highLightByAppDTO, HighLightRecord.class);

            if(StringUtils.isNotBlank(hightLightId)){
                highLightRecord.setId(hightLightId);
            }else {
                highLightRecord.setId(IdGenerator.uuid2().toString());
            }

            highLightRecord.setUploadImageList(getUploadImage(highLightByAppDTO.getUploadImageList()));

            highLightRecord.setGmtCreated(new Date());
            highLightRecord.setGmtModified(new Date());

            HighLightRecord newHighLightRecord = highLightRepository.save(highLightRecord);
            if (newHighLightRecord == null) {
                throw new HandlerException(ConstEum.FAIL, ConstEum.FAIL.getMessage());
            }
        }else{
            try {
                highLightRepository.deleteByCheckId(checkRecord.getId());
            }catch (Exception e){}
        }

        if(checkRecordOffLineByAppDTO.getHiddendangerByAppDTOS()!=null &&
                checkRecordOffLineByAppDTO.getHiddendangerByAppDTOS().size()>0){
            for (HiddendangerByAppDTO hiddendangerByAppDTO:checkRecordOffLineByAppDTO.getHiddendangerByAppDTOS()){

                String hiddenDangerId="";
                if (StringUtils.isNotBlank(hiddendangerByAppDTO.getId())) {
                    HiddendangerRecord hiddendangerRecord = hiddenDangerRecordRepository.findOne(hiddendangerByAppDTO.getId());
                    if (hiddendangerRecord == null) {
//                        throw new HandlerException(ConstEum.FAIL, "错误的隐患Id");
                    }else
                    {
                        hiddenDangerId=hiddendangerRecord.getId();
                        hiddenDangerRecordRepository.delete(hiddendangerRecord.getId());
                    }
                }
                HiddendangerRecord hiddendangerRecord = BeanMapper.map(hiddendangerByAppDTO, HiddendangerRecord.class);
                if(StringUtils.isNotBlank(hiddenDangerId)){
                    hiddendangerRecord.setId(hiddenDangerId);
                    hiddendangerRecord.setOffline(null);
                }else {
                    hiddendangerRecord.setId(IdGenerator.uuid2().toString());
                }

                hiddendangerRecord.setHiddenDangerStatus(CommonDbConst.HIDDENDANGER_STATUS_READY_RECTIFY);

                if (StringUtils.isNotBlank(hiddendangerRecord.getCheckLabId())) {
                    //查询所属所室
                    LaboratoryDomain laboratoryDomain = laboratoryRepository.findOne(hiddendangerRecord.getCheckLabId().toString());
                    if (laboratoryDomain != null) {
                        hiddendangerRecord.setOffices(laboratoryDomain.getOffices());
                    }

                }
                //检查记录状态
                hiddendangerRecord.setCheckStatus(checkRecord.getCheckStatus());
                //检查记录日期
                hiddendangerRecord.setCheckDate(checkRecord.getCheckDate());

                //保存图片
                hiddendangerRecord.setUploadImageList(getUploadImage(hiddendangerByAppDTO.getUploadImageList()));


                hiddendangerRecord.setGmtCreated(new Date());
                hiddendangerRecord.setGmtModified(new Date());

                HiddendangerRecord newHiddendangerRecord = hiddenDangerRecordRepository.save(hiddendangerRecord);
                if (newHiddendangerRecord == null) {
                    throw new HandlerException(ConstEum.FAIL, ConstEum.FAIL.getMessage());
                }

            }
        }
        //处理隐患完成后，检查该检查记录下是否还有离线的隐患记录,有就删除
        List<HiddendangerRecord> hiddendangerRecordList=
                hiddenDangerRecordRepository.findHiddendangerRecordByCheckIdAndOffline(checkRecord.getId(),"0");
        for (HiddendangerRecord h:hiddendangerRecordList){
            hiddenDangerRecordRepository.delete(h.getId());
        }
    }

    /**
     * 根据检查人员id,获取检查人员详情
     *
     * @param checkRecordOffLineByAppDTO
     * @return
     */
    private ArrayList<CheckUser> getCheckUser(CheckRecordOffLineByAppDTO checkRecordOffLineByAppDTO) {
        ArrayList<CheckUser> checkUsers = new ArrayList<CheckUser>();
        for (String id : checkRecordOffLineByAppDTO.getCheckUserId()) {
            UserInfo userInfo = userInfoRepository.findOne(id.toString());
            if (userInfo != null) {
                CheckUser checkUser = BeanMapper.map(userInfo, CheckUser.class);
                checkUsers.add(checkUser);
            }
        }
        return checkUsers;
    }


    private List<UploadImage> getUploadImage(List<UploadImageDTO> arrayList)
    {
        ArrayList<UploadImage> uploadImages = new ArrayList<UploadImage>();
        for(UploadImageDTO uploadImageDTO :arrayList) {
            if(uploadImageDTO!=null && StringUtils.isNotBlank(uploadImageDTO.getId())) {
                UploadImage uploadImage = imageRepository.findOne(uploadImageDTO.getId());
                if(uploadImage==null)
                {
                    throw new HandlerException(ConstEum.FAIL,"无效的图片");
                }
                uploadImages.add(uploadImage);
            }
        }
        return uploadImages;

    }
}
